package com.seckill.common.service;


import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

/**
 * 本地缓存类
 *
 * @author lill
 * @date 2019-07-01
 */
@Component
public class LocalCacheService<T> {

    private Cache<String, T> localCache = null;

    @PostConstruct
    public void init() {
        localCache = CacheBuilder.newBuilder()
                // 设置缓存容器的初始容量为10
                .initialCapacity(10)
                // 设置缓存中最大可以存储100个KEY,超过100个之后会按照LRU的策略移除缓存项
                .maximumSize(100)
                // 设置写缓存后多少秒过期
                .expireAfterWrite(10, TimeUnit.SECONDS).build();
    }

    public void setLocalCache(String key, T value) {
        localCache.put(key, value);
    }


    public T getLocalCache(String key) {
        return localCache.getIfPresent(key);
    }

}
